using System.Xml.Linq;
using Engine;
using Game;
using SCIENEW.Tech;

namespace SCIENEW {
    public class TechTreeScreen : Screen {
        public TechTree m_techTree;

        public CanvasWidget m_treeView;

        public BevelledButtonWidget m_thanksButton;

        public BevelledButtonWidget m_staticButton;

        public TechTreeNodeInfoWidget m_nodeInfoWidget;

        public TechTreeBackgroundWidget m_background;

        public Dictionary<TechNode, TechTreeNodeWidget> m_nodeWidgets = new();

        public TechNode m_selectedNode;

        public Screen m_previousScreen;

        public TechTreeScreen() {
            XElement node = ContentManager.Get<XElement>("Screens/TechTreeScreen");
            LoadContents(this, node);
            m_treeView = Children.Find<CanvasWidget>("TreeView");
            m_nodeInfoWidget = Children.Find<TechTreeNodeInfoWidget>("NodeInfo");
            m_staticButton = Children.Find<BevelledButtonWidget>("StaticBackgroundButton");
            m_thanksButton = Children.Find<BevelledButtonWidget>("ThanksButton");
            m_background = Children.Find<TechTreeBackgroundWidget>("BG");
        }

        public override void Enter(object[] parameters) {
            if (ScreensManager.PreviousScreen == ScreensManager.FindScreen<Screen>("RecipaediaRecipes") || ScreensManager.PreviousScreen == ScreensManager.FindScreen<Screen>("RecipaediaDescription"))
                return;
            this.m_previousScreen = ScreensManager.PreviousScreen;
            m_techTree = (TechTree)parameters[0];
            m_selectedNode = null;
            UpdateTreeView();
        }

        void UpdateTreeView() {
            int xSpacing = 200;
            int ySpacing = 90;

            m_treeView.Size = new Vector2(12000, 400);
            //m_treeView.Children.Add(new RectangleWidget(){FillColor = Color.Cyan});
            m_treeView.VerticalAlignment = WidgetAlignment.Center;
            //添加节点
            int stage = 0;
            TechNode[] nodeByStage;
            do {
                nodeByStage = m_techTree.GetNodeByStage(stage);

                //添加节点
                for (int i = 0; i < nodeByStage.Length; i++) {
                    TechTreeNodeWidget nodeWidget = new(nodeByStage[i]);
                    nodeWidget.OnClicked += OnNodeClicked;
                    float x = xSpacing + stage * xSpacing;
                    float centerY = m_treeView.Size.Y / 2 - nodeWidget.Size.Y / 2;
                    float yOffset = nodeByStage.Length % 2 == 1 ? (i - MathF.Floor(nodeByStage.Length / 2f)) * ySpacing : (i - (nodeByStage.Length / 2f - 0.5f)) * ySpacing;
                    float y = yOffset + centerY;

                    m_treeView.Children.Add(nodeWidget);
                    m_nodeWidgets[nodeByStage[i]] = nodeWidget;
                    m_treeView.SetWidgetPosition(nodeWidget, new Vector2(x, y) + nodeByStage[i].LayoutOffset);
                }

                stage++;
            }
            while (nodeByStage.Length > 0);

             //添加边
             foreach (var nodePair in m_nodeWidgets) {
                 TechNode techNode = nodePair.Key;
                 foreach (var dependencyNode in techNode.Dependencies) {
                     TechTreeNodeWidget fromNode = m_nodeWidgets[dependencyNode];
                     TechTreeNodeWidget toNode = nodePair.Value;
                     Vector2 fromPoint = m_treeView.GetWidgetPosition(fromNode)!.Value + new Vector2(fromNode.Size.X + 6, fromNode.Size.Y / 2);
                     Vector2 toPoint = m_treeView.GetWidgetPosition(toNode)!.Value + new Vector2(-6, toNode.Size.Y / 2);
                     Vector2 upLeft = new Vector2(MathF.Min(fromPoint.X, toPoint.X), MathF.Min(fromPoint.Y, toPoint.Y));
                     Vector2 downRight = new Vector2(MathF.Max(fromPoint.X, toPoint.X), MathF.Max(fromPoint.Y, toPoint.Y));
                     ArrowLineWidget arrow = new ArrowLineWidget() {Color = new Color(64, 150, 200), ArrowWidth = 4, Width = 4, PointsString = $"{fromPoint.X},{fromPoint.Y};{toPoint.X},{toPoint.Y}", ClampToBounds = true};
                     m_treeView.Children.Add(arrow);
                     m_treeView.SetWidgetPosition(arrow, upLeft);
                 }
             }
        }

        public override void Update() {
            m_nodeInfoWidget.m_node = m_selectedNode;
            m_staticButton.Text = m_staticButton.IsChecked ? "静态背景:开" : "静态背景:关";
            m_background.IsStatic = m_staticButton.IsChecked;

            if (m_thanksButton.IsClicked) {
                DialogsManager.ShowDialog(this, new MessageDialog("感谢以下玩家对科技树建立做出贡献", "悟诗守禅哒(bilibili430597594)\r\nmmmmmooo(QQ2606235417)\r\n欧耶(QQ669468050)\r\n玖\uff1c月\uff1e(QQ2390735361)", "OK", null, null));
            }


            if (m_nodeInfoWidget.m_node != null) {
                if (m_nodeInfoWidget.m_recipeButton.IsClicked) {
                    ScreensManager.SwitchScreen("RecipaediaRecipes", m_nodeInfoWidget.m_node.IconBlock);
                }
                if (m_nodeInfoWidget.m_descButton.IsClicked) {
                    ScreensManager.SwitchScreen("RecipaediaDescription", m_nodeInfoWidget.m_node.IconBlock, m_nodeWidgets.Keys.Select(x => x.IconBlock).ToList());
                }
            }

            if (Input.Back
                || Input.Cancel
                || Children.Find<ButtonWidget>("TopBar.Back").IsClicked) {
                ScreensManager.SwitchScreen(m_previousScreen);
            }
        }

        public void OnNodeClicked(TechNode techNode) {
            m_selectedNode = techNode;
            foreach (var nodeToWidget in m_nodeWidgets) {
                nodeToWidget.Value.IsChecked = nodeToWidget.Key == techNode;
            }
        }
    }
}